using System;
using System.Collections.Generic;
using System.Diagnostics;
using TAAlert.CommonUtils;

namespace TAAlert.BackTest
{
    class MACDStrategy : Strategy
    {
        static private readonly TraceSwitch traceM = new TraceSwitch("MACDStrategy", "Debug info for MACD Strategy class");
        private List<double> macdHistogramM;

        /// <summary>MACD Strategy based on sign of MACD historgram. BUY if histogram is positive, SELL if histogram is negative</summary>
        /// <param name="nEMAShort">period for short EMA average</param>
        /// <param name="nEMALong">period for long EMA average</param>
        /// <param name="nFast">period for FAST EMA average</param>
        /// <param name="startDate">Start date of the investment strategy</param>
        /// <param name="endDate">End date of the investmetn strategy</param>
        /// <param name="prices">Dated list of closing prices for the underlying. It should start well before startDate</param>
        public MACDStrategy(int nEMAShort, int nEMALong, int nFast, DateTime startDate, DateTime endDate, SortedList<DateTime, double> prices)
            : base(startDate, endDate, prices, traceM)
        {
            Debug.WriteLineIf(traceM.TraceInfo, "--> Entering MACDStrategy(nShort=" + nEMAShort + ", nLong=" + nEMALong + ", nFast=" + nFast + ", start=" + startDate.ToShortDateString() + ", end=" + endDate.ToShortDateString() + ", prices.Count=" + prices.Count + ")");
            this.macdHistogramM = MACDEvaluator.calcMacdHistogram(this.Prices.Values, nEMAShort, nEMALong, nFast);
        }

        override public SortedList<DateTime, int> generate()
        {
            Debug.WriteLineIf(traceM.TraceInfo, "--> Entering EMAStrategy.generate()");
            Debug.Indent();
            int n = this.EndIx - this.StartIx + 1;

            SortedList<DateTime, int> pos = new SortedList<DateTime, int>(n);
            Debug.WriteLineIf(traceM.TraceVerbose, "Date,Price,macdHist,Position");
            for (int ix = this.StartIx; ix <= this.EndIx; ++ix)
            {
                DateTime date = this.Prices.Keys[ix];
                int signal = (int)MACDEvaluator.macdSignal(macdHistogramM, ix);
                pos.Add(date, signal);
                Debug.WriteLineIf(traceM.TraceVerbose, date.ToShortDateString() + ", " + this.Prices.Values[ix].ToString(".##") + ", " + macdHistogramM[ix].ToString(".##") + ", " + signal);
            }
            Debug.WriteLineIf(traceM.TraceInfo, "... generated " + pos.Count + " signals");
            Debug.Unindent();
            return pos;
        }

    }
}
